package hxy.cupb.service.impl;

//import hxy.cupb.entity.UserDetails;
import hxy.cupb.entity.UserEntity;
import hxy.cupb.entity.dto.UserEntityDTO;
import hxy.cupb.mapper.UserMapper;
import hxy.cupb.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService ,UserService {

    @Autowired(required = false)
    UserMapper userMapper;


    /**SpringSecurity的UserDetailsService接口的方法有Spring管理，所以不是由哪个Controller接入！在自己写的代码里不存在调用这个方法，这个方法是实现UserDetailsService的接口，也即是Spring自己管理调用了
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userMapper.loadUserByUserName(username);
        if (userEntity==null){
//        if (userEntity!=null){  // 自己的疏忽写成了 !=
            log.warn("账户信息不存在");
            throw new UsernameNotFoundException("账户不存在");
        }
        userEntity.setRoles(userMapper.getUserRolesByUid(userEntity.getId()));
        if (log.isDebugEnabled()){
            log.debug("用户信息{}",userEntity);
        }
        return userEntity;
    }

    @Override
    public List<UserEntityDTO> findAll() {
      List<UserEntity> list =  userMapper.findAll();
      List<UserEntityDTO> list1 =new UserEntityDTO().convertListFor(list);
        return list1;
    }

    @Override
    public UserEntityDTO findUserEntityDTOById(int id) {
        return null;
    }

    /**
     * @Description：自己写的UserService接口的方法，可以由Controller调用。
     * @param userName
     * @return
     */
    @Override
    public UserEntity loadUserByUserName(String userName) {
        UserEntity userEntity = userMapper.loadUserByUserName(userName);
        if (userEntity!=null){
            throw new UsernameNotFoundException("账户不存在");
        }
        userEntity.setRoles(userMapper.getUserRolesByUid(userEntity.getId()));
        return userEntity;
    }

}
